package com.vercon.moensmart.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.wifi.ScanResult
import android.os.Handler
import android.provider.Settings
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.airbnb.lottie.LottieDrawable
import com.google.gson.Gson
import com.vercon.common.Constants
import com.vercon.common.mode.common.BaseMode
import com.vercon.common.mode.event.WifiSuccessEvent
import com.vercon.common.mode.weather.AirAuality
import com.vercon.common.mode.weather.NewWeatherSimpleBean
import com.vercon.common.presenter.MainPresenter
import com.vercon.common.presenter.common.MirrorResultView
import com.vercon.common.utils.LogUtils
import com.vercon.common.utils.MirrorDataStorage
import com.vercon.common.utils.WeatherUtils
import com.vercon.common.wifi.EasyzcWifi.Companion.get
import com.vercon.common.wifi.EasyzcWifiStateListener
import com.vercon.moensmart.MainActivity
import com.vercon.moensmart.MainApplication
import com.vercon.moensmart.R
import com.vercon.moensmart.WebKitWebViewActivity
import com.vercon.moensmart.adapter.FollowMemberAdapter
import com.vercon.moensmart.adapter.IndicatorAdapter
import com.vercon.moensmart.adapter.MultiViewTypesAdapter
import com.vercon.moensmart.adapter.SmartDeviceListAdapter
import com.vercon.moensmart.adapter.base.BaseAdapter
import com.vercon.moensmart.databinding.FragmentHomeLayoutBinding
import com.vercon.moensmart.dialog.TowelRackControllerDialog
import com.vercon.moensmart.event.AppDeleteEvent
import com.vercon.moensmart.event.BaseEvent
import com.vercon.moensmart.fragment.base.BaseFragment
import com.vercon.moensmart.fragment.manager.FragmentOpenManager
import com.vercon.moensmart.mode.HealthChartDate
import com.vercon.moensmart.mode.HealthChartDate2
import com.vercon.moensmart.mode.HealthMeasureTarget
import com.vercon.moensmart.mode.MenuStateBean
import com.vercon.moensmart.mode.response.AllDevices
import com.vercon.moensmart.mode.response.BaseResponse
import com.vercon.moensmart.mode.response.FollowMember
import com.vercon.moensmart.mode.response.HealthMeasure
import com.vercon.moensmart.mode.response.Inspiration
import com.vercon.moensmart.mode.response.MeasureTrendChart
import com.vercon.moensmart.mode.response.UserInfo
import com.vercon.moensmart.presenter.MoenPresenter
import com.vercon.moensmart.utils.AppUtil
import com.vercon.moensmart.utils.FrescoUtil
import com.vercon.moensmart.utils.LightHelper
import com.vercon.moensmart.utils.PreferenceUtils
import com.vercon.moensmart.utils.ToastUtils
import com.vercon.moensmart.utils.WebsocketMoen
import com.vercon.moensmart.view.EchartsView
import com.vercon.moensmart.viewmodel.DeviceControllerViewModel
import com.vercon.moensmart.viewmodel.SystemViewModel
import com.zhpan.bannerview.BannerViewPager
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date
import java.util.concurrent.TimeUnit


class HomeFragment : BaseFragment<FragmentHomeLayoutBinding?>(),
    EasyzcWifiStateListener {
    var chartInflateView: View? = null
    var webviewEcharts : EchartsView? = null
    var followMemberRecyclerView : RecyclerView? = null
    var tv_weight : TextView? = null
    var tv_measure_update_time : TextView? = null
    var tv_current_data_user_name : TextView? = null
    var v_i_know_had_new_health_data : View? = null
    var ll_show_new_health_data_tip : LinearLayout? = null
    var mainPresenter: MainPresenter? = null
    var weatherDisposable: Disposable? = null
    var demistDisposable: Disposable? = null
    var deviceListAdapter: SmartDeviceListAdapter? = null
    var followMemberAdapter : FollowMemberAdapter? = null

    var indicatorAdapter: IndicatorAdapter? = null
    var temperatureValue = 26
    var openSetting = 0
    var currentAdIndex = 0
    var websocketMoen : WebsocketMoen? = null
    var moenPresenter = MoenPresenter()
    var systemViewModel : SystemViewModel? = null
    var deviceControllerViewModel : DeviceControllerViewModel? = null
    var rl_follow_member :RelativeLayout? = null
    var isWebLoaded = false
    val sdf = SimpleDateFormat("yyyy-MM-dd")
    private val SETTING_GPIO3 = "setting_system_gpio3" //

    override fun onCreateViewBinding(inflater: LayoutInflater, parent: ViewGroup?): FragmentHomeLayoutBinding {
        return FragmentHomeLayoutBinding.inflate(inflater, parent, false)
    }

    @SuppressLint("SetJavaScriptEnabled")
    override fun initData() {
        EventBus.getDefault().register(this@HomeFragment)
        get().addListener(this)
        get().refresh()
        binding?.homeWeatherLayout?.tcTime?.format24Hour = "HH:mm"
        binding?.homeWeatherLayout?.tcTime?.format12Hour = null
        mainPresenter = MainPresenter()
        deviceListAdapter = SmartDeviceListAdapter(context)
        binding?.smartDeviceListLayout?.smartDeviceListRecyclerView?.adapter = deviceListAdapter


        deviceControllerViewModel = ViewModelProvider(requireActivity())[DeviceControllerViewModel::class.java]

        systemViewModel = ViewModelProvider(requireActivity())[SystemViewModel::class.java]
        systemViewModel?.loadAppModeList()

        var token = MirrorDataStorage.instance().getString(Constants.STORAGE_KEY_TOKEN,"")
        if(token.isNullOrEmpty()){
            val uri = Uri.parse("https://dsada33")
            FrescoUtil.loadCircleImage(binding?.ifUserHeadPortrait,uri,context)
        }

        chartInflateView = binding?.smartDeviceChartLayout?.inflate()
        tv_current_data_user_name = chartInflateView?.findViewById(R.id.tv_current_data_user_name)
        v_i_know_had_new_health_data = chartInflateView?.findViewById(R.id.v_i_know_had_new_health_data)
        ll_show_new_health_data_tip = chartInflateView?.findViewById(R.id.ll_show_new_health_data_tip)
        tv_weight = chartInflateView?.findViewById(R.id.tv_weight)
        tv_measure_update_time = chartInflateView?.findViewById(R.id.tv_measure_update_time)
        followMemberRecyclerView = chartInflateView?.findViewById(R.id.follow_member_recycler_view)
        val ll_to_see_follow_member : LinearLayout? = chartInflateView?.findViewById(R.id.ll_to_see_follow_member)
        rl_follow_member  = chartInflateView?.findViewById(R.id.rl_follow_member)
        ll_to_see_follow_member?.setOnClickListener {
            rl_follow_member?.visibility =  View.VISIBLE
        }
        rl_follow_member?.setOnClickListener {
            rl_follow_member?.visibility =  View.GONE
        }


        webviewEcharts = chartInflateView!!.findViewById(R.id.webview_echarts)
        webviewEcharts?.setBackgroundColor(0)
        webviewEcharts?.background?.alpha = 0

        indicatorAdapter = IndicatorAdapter(context)
        binding?.adWebLayout?.indicatorRecyclerView?.adapter = indicatorAdapter

        binding?.adWebLayout?.bannerView?.setScrollDuration(600)
            ?.setOffScreenPageLimit(2)
            ?.setInterval(8000)
            ?.setIndicatorVisibility(View.GONE)
            ?.disallowParentInterceptDownEvent(true)
            ?.setAdapter( MultiViewTypesAdapter())
            ?.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    currentAdIndex =position
                    indicatorAdapter?.setCurrentIndex(currentAdIndex)
                    try {
                        val data = binding?.adWebLayout?.bannerView?.data?.get(currentAdIndex) as Inspiration.ListDTO
                        if(data.link?.length!! > 4 && data.link?.substring(0,4).equals("http")){
                            binding?.adWebLayout?.igGotAdWeb?.visibility =View.VISIBLE
                        }else {
                            binding?.adWebLayout?.igGotAdWeb?.visibility =View.GONE
                            //ToastUtils.showToast("链接错误")
                        }
                    }catch (e:Exception){
                        e.printStackTrace()
                    }
                }
            })
            ?.setOnPageClickListener(object : BannerViewPager.OnPageClickListener{
                override fun onPageClick(clickedView: View?, position: Int) {
                    try {
                        val data = binding?.adWebLayout?.bannerView?.data?.get(position) as Inspiration.ListDTO
                        if(data.link?.length!! > 4 && data.link?.substring(0,4).equals("http")){
                            val intent = Intent(activity, WebKitWebViewActivity::class.java)
                            intent.putExtra(WebKitWebViewActivity.WEB_URL, data.link)
                            startActivity(intent)
                        }else {
                            //ToastUtils.showToast("链接错误")
                        }
                    }catch (e:Exception){
                        e.printStackTrace()
                    }
                }

            })
            ?.create()


        //广告位轮播
        getMoenAdList()

        followMemberAdapter = FollowMemberAdapter(context)
        followMemberRecyclerView?.adapter = followMemberAdapter
    }

    override fun initListener() {

        binding?.ifUserHeadPortrait?.setOnClickListener {
            var token = MirrorDataStorage.instance().getString(Constants.STORAGE_KEY_TOKEN,"")
            if(token.isNullOrEmpty()){
                FragmentOpenManager.getInstance().goToLoginFragment(requireActivity())
            }else{
//                val popupWindow = UserEditPopupWindow(requireContext(),childFragmentManager)
//                popupWindow.setUserEdtPopupWindowListener(object : UserEditPopupWindow.UserEdtPopupWindowListener{
//                    override fun onGotoLogin() {
//
//                    }
//
//                    override fun onExit() {
//                        //Fresco 清除缓存
//                        val imagePipeline = ImagePipelineFactory.getInstance().imagePipeline
//                        imagePipeline.clearMemoryCaches()
//                        imagePipeline.clearDiskCaches()
//                        imagePipeline.clearCaches()
//                        MirrorDataStorage.instance().storeString(Constants.STORAGE_KEY_TOKEN,"")
//                        systemViewModel?.setUserTokenLiveData(null)
//                    }
//
//                    override fun onCancle() {
//
//                    }
//
//                })
//                popupWindow.showPopupWindow()
            }
        }

        binding?.rlMirrorMode?.setOnClickListener {  }
        binding?.tvMirrorMode?.setOnClickListener {
            binding?.rlMirrorMode?.visibility = View.GONE
        }

        //音乐
        binding?.musicLayout?.root?.setOnClickListener {
            AppUtil.openOtherApp(MainApplication.getContext(),"com.tencent.qqmusiccar")
        }

        //视频
        binding?.videoLayout?.root?.setOnClickListener {
            AppUtil.openOtherApp(MainApplication.getContext(),"com.kwai.tv.yst")
        }


        //应用中心
        binding?.moreAppLayout?.root?.setOnClickListener {
            activity?.let { FragmentOpenManager.getInstance().addFragment(it, AppFragment()) }
        }
        binding?.mirrorModeLayout?.root?.setOnClickListener {
            binding?.rlMirrorMode?.visibility = View.VISIBLE
        }

        //灯光
        val menuStateBean: MenuStateBean? = PreferenceUtils.getMenuState()
        binding?.lightSwitchLayout?.igLightState?.isSelected = menuStateBean!!.light_switch
        binding?.lightSwitchLayout?.igDetails?.setOnClickListener {
            activity?.let { FragmentOpenManager.getInstance().addFragment(it, LightFragment()) }
        }
        binding?.lightSwitchLayout?.rlSwitch?.setOnClickListener {
            binding?.lightSwitchLayout?.igLightState?.isSelected = !binding?.lightSwitchLayout?.igLightState?.isSelected!!
            var menuStateBean: MenuStateBean? = PreferenceUtils.getMenuState()
            if(binding?.lightSwitchLayout?.igLightState?.isSelected!!){
                if(menuStateBean!!.light_data == 0){
                    menuStateBean!!.light_data = LightFragment.LIGHT_SWITCH_INIT_VALUE
                }
                LightHelper.getInstance().controlLight(context, true, true, menuStateBean!!.light_data, menuStateBean.light_color)
            }else{
               LightHelper.getInstance().controlLightClose(context, true)
            }
            menuStateBean?.light_switch = binding?.lightSwitchLayout?.igLightState?.isSelected!!
            PreferenceUtils.setData(PreferenceUtils.MenuState,menuStateBean)
        }

        //除雾
        binding?.demistSwitchLayout?.igDetails?.setOnClickListener {
            activity?.let { FragmentOpenManager.getInstance().addFragment(it, DemistFragment()) }
        }
        binding?.demistSwitchLayout?.rlSwitch?.setOnClickListener {
            binding?.demistSwitchLayout?.igDemistState?.isSelected = !binding?.demistSwitchLayout?.igDemistState?.isSelected!!
            EventBus.getDefault().post(BaseEvent(Constants.refreshDemist,binding?.demistSwitchLayout?.igDemistState?.isSelected!!))
            if(binding?.demistSwitchLayout?.igDemistState?.isSelected!!){
                systemViewModel?.setIsOpenDemist(true,null)
            }else{
                systemViewModel?.setIsOpenDemist(false,null)
            }
        }
        systemViewModel?.isOpenDemist?.observe(this@HomeFragment) {
            if(it){
                Settings.System.putInt(context?.contentResolver, SETTING_GPIO3,1)
                demistTask()
            }else{
                Settings.System.putInt(context?.contentResolver, SETTING_GPIO3,0)
                disposeDemistTask()
            }
        }
        //天气
        autoGetWeather()
        Observable.interval(1, TimeUnit.HOURS).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<Long?> {
                override fun onSubscribe(d: Disposable) {
                    weatherDisposable = d
                }

                override fun onNext(t: Long) {
                    autoGetWeather()
                }

                override fun onError(e: Throwable) {}
                override fun onComplete() {}
            })


        getAllData()

        systemViewModel?.currentUserIdLiveData?.observe(this@HomeFragment){
            //全部设备
            getAllDevice()
            //查看成员
            followMember()
            //最近测量数据
            getHealthMeasureData(if(systemViewModel?.loginUserId.equals(it)) null else it)
            //测量趋势图
            getHealthChart(if(systemViewModel?.loginUserId.equals(it)) null else it)
        }
        systemViewModel?.followMemberLiveData?.observe(this@HomeFragment){value->
            if(value != null){
                followMemberAdapter?.setData(value.list)
                systemViewModel?.currentUserIdLiveData?.value?.let { followMemberAdapter?.setCurrentId(it) }
                for ((i,bean) in value.list.withIndex()){
                    if(bean.pk.equals(systemViewModel?.currentUserIdLiveData?.value)){
                        tv_current_data_user_name?.text = bean!!.nickname + "的数据"
                    }
                }
            }else{
                followMemberAdapter?.setData(ArrayList())
                followMemberAdapter?.setCurrentId("")
            }
        }
        systemViewModel?.webSocketLiveData?.observe(this){
            it?.let {
                try {
                    val jsonObject = JSONObject(it)
                    try {
                        val product_id = jsonObject.getString("product_id")
                        val device_id = jsonObject.getString("device_id")
                        if(!device_id.isNullOrEmpty() && !product_id.isNullOrEmpty()){
                            val stateJson = jsonObject.getJSONObject("state")
                            val reportedJson = stateJson.getJSONObject("reported")

                            val connectTypeStr = reportedJson.getString("ConnectType")
                            deviceListAdapter?.refreshDeviceState((if(connectTypeStr.equals("online")) 1 else 0) ,device_id)

                            if(product_id.equals("A87FI1")){

                            }else if(product_id.equals("ZMJTJP")){
                                val power = reportedJson.getInt("power")
                                deviceControllerViewModel?.setTowelRack_PowerSwitch(device_id,power)
                                val temperature_set = reportedJson.getInt("temperature_set")
                                when(temperature_set){
                                    45->{
                                        deviceControllerViewModel?.setTowelRack_Temperature(device_id,0)
                                    }
                                    55->{
                                        deviceControllerViewModel?.setTowelRack_Temperature(device_id,1)
                                    }
                                    65->{
                                        deviceControllerViewModel?.setTowelRack_Temperature(device_id,2)
                                    }
                                    else -> {}
                                }
                                val time_set = reportedJson.getInt("time_set")
                                deviceControllerViewModel?.setTowelRack_Time(device_id,time_set)
                            }

                        }
                    }catch (e : Exception){
                        e.printStackTrace()
                    }
                    when(jsonObject.getInt("type")){
                        2->{ getAllDevice() } //解绑
                        3->{ //设备在离线
                            val is_online = jsonObject.getInt("is_online")
                            val device_id = jsonObject.getString("device_id")
                            deviceListAdapter?.refreshDeviceState(is_online,device_id)
                        }
                        4->{  //邀请成员
                            followMember()
                            systemViewModel?.setCurrentUserIdLiveData(systemViewModel?.loginUserId)
                        }
                        9->{ //被测量数据主⽤户移除查看权限
                            followMember()
                            systemViewModel?.setCurrentUserIdLiveData(systemViewModel?.loginUserId)
                        }
                        10->{ //⽤户测量数据已⼊数据库
                            val enduser_id = jsonObject.getString("enduser_id")
                            if(enduser_id.equals(systemViewModel?.currentUserIdLiveData?.value)){
                                //ToastUtils.showToast("你有新的健康数据")
                                ll_show_new_health_data_tip?.visibility = View.VISIBLE
                                //最近测量数据
                                getHealthMeasureData(if(systemViewModel?.loginUserId.equals(enduser_id)) null else enduser_id)
                                //测量趋势图
                                getHealthChart(if(systemViewModel?.loginUserId.equals(enduser_id)) null else enduser_id)
                            }
                        }
                    }
                }catch (e : Exception){
                    e.printStackTrace()
                }

            }
        }

        v_i_know_had_new_health_data?.setOnClickListener {
            ll_show_new_health_data_tip?.visibility = View.GONE
        }
    }

    private fun getAllData(){
        systemViewModel?.userTokenLiveData?.observe(this@HomeFragment) {
            if(!it.isNullOrEmpty()){
                //用户数据
                getUserInfo()
                websocketInit()
            }else{
                deviceControllerViewModel?.clearTowelRackList()

                websocketMoen?.cancel()
                val uri = Uri.parse("https://dsada33")
                FrescoUtil.loadCircleImage(binding?.ifUserHeadPortrait,uri,context)
                binding?.tvUserName?.text = ""
                deviceListAdapter?.setData(ArrayList())
                systemViewModel?.setFollowMemberLiveData(null)
                tv_weight?.text = "--"
                tv_measure_update_time?.text = "最近测量:--"
                tv_current_data_user_name?.text = "--"
                systemViewModel?.setHealthMeasureLiveData(null)

                var healthChartDate = HealthChartDate2()
                var xLabel = ArrayList<String>()
                var yData = ArrayList<Int>()

                healthChartDate.Data = yData
                healthChartDate.xLabel = xLabel
                webviewEcharts?.init("file:///android_asset/EChartView.html")
                webviewEcharts?.setWebViewClient(object : WebViewClient() {
                    override fun onPageFinished(view: WebView, url: String) {
                        super.onPageFinished(view, url)
                        webviewEcharts?.refreshEchartsWithOption(healthChartDate)
                    }

                    override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
                        super.onPageStarted(view, url, favicon)
                    }
                })
            }
        }
    }



    private fun websocketInit(){
        websocketMoen = WebsocketMoen()
        websocketMoen?.WSinit()
        websocketMoen?.setListener {
            if(!it.isNullOrEmpty()){
                Observable.timer(0,TimeUnit.SECONDS).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<Long?> {
                        override fun onSubscribe(d: Disposable) {

                        }

                        override fun onNext(t: Long) {
                            systemViewModel?.setWebsocketLiveData(it)
                        }

                        override fun onError(e: Throwable) {}
                        override fun onComplete() {}
                    })
            }
        }
    }


    override fun onClick(v: View?) {}

    /**
     * 用户数据
     */
    private fun getUserInfo(){
        moenPresenter.getUserInfo(object : MirrorResultView<BaseResponse<UserInfo>>{
            override fun onSuccess(result: BaseResponse<UserInfo>?) {
                if(result?.isSuccessful!!){
                    binding?.tvUserName?.text = result.data.nickname
                    if(result.data?.profile_photo.isNullOrEmpty()){
                        FrescoUtil.loadDetailsCircleImage(binding?.ifUserHeadPortrait,Uri.parse(result.data?.profile_photo),context)
                    }else{
                        FrescoUtil.loadCircleImage(binding?.ifUserHeadPortrait,Uri.parse(result.data?.profile_photo),context)
                    }

                    tv_current_data_user_name?.text = result.data.nickname + "的数据"
                    systemViewModel?.setCurrentUserIdLiveData(result?.data?.enduser_id)
                    systemViewModel?.loginUserId = result?.data?.enduser_id
                }
            }
            override fun onError(code: Int, message: String?) {

            }
        })
    }


    /**
     * 全部设备
     */
    private fun getAllDevice(){
        deviceListAdapter?.setItemOnClickListener(object : BaseAdapter.BaseItemListener<AllDevices.ListDTO?>{
            override fun onItemClickListener(v: View?, data: AllDevices.ListDTO?, position: Int) {

            }
        })
        moenPresenter.getAllDevice(object : MirrorResultView<BaseResponse<AllDevices>>{
            override fun onSuccess(result: BaseResponse<AllDevices>?) {
                if(result?.isSuccessful!!){
                    var hadTollet = false
                    var hadTowelRack = false
                    for ( (i,bean) in result.data?.list!!.withIndex()){


                        if(bean.product_id.equals("A87FI1")){
                            bean.product_series = "智能坐便器"
                            bean.device_alias = "M-Link"
                            hadTollet = true
                        }else if(bean.product_id.equals("ZMJTJP")){
                            bean.product_series = "智能毛巾架"
                            bean.device_alias = "M-Link"
                            hadTowelRack = true

                            deviceControllerViewModel?.setTowelRackLiveData(bean.device_id)
                        }
                    }
                    if(!hadTollet){
                        result.data?.list!!.add(AllDevices.ListDTO("","M-Link","A87FI1","智能坐便器",1))
                    }
                    if(!hadTowelRack){
                        result.data?.list!!.add(AllDevices.ListDTO(TowelRackControllerDialog.DEMO_DEVICE_ID,"M-Link","ZMJTJP","智能毛巾架",1))
                        deviceControllerViewModel?.setTowelRackLiveData(TowelRackControllerDialog.DEMO_DEVICE_ID)
                    }
                    result.data?.list!!.add(AllDevices.ListDTO("","M-Link","2","智能花洒",-1))
                    deviceListAdapter?.setData(result.data?.list)
                }
            }
            override fun onError(code: Int, message: String?) {

            }
        })
    }

    /**
     * 成员列表
     */
    private fun followMember(){
        followMemberAdapter?.setItemOnClickListener(object : BaseAdapter.BaseItemListener<FollowMember.ListDTO?>{
            override fun onItemClickListener(v: View?, data: FollowMember.ListDTO?, position: Int) {
                followMemberAdapter?.setCurrentId(data!!.pk)
                systemViewModel?.setCurrentUserIdLiveData(data?.pk)
                tv_current_data_user_name?.text = data!!.nickname + "的数据"
                rl_follow_member?.visibility =  View.GONE
            }
        })
        moenPresenter.followMember(object : MirrorResultView<BaseResponse<FollowMember>>{
            override fun onSuccess(result: BaseResponse<FollowMember>?) {
               if(result?.isSuccessful!!){
                   systemViewModel?.setFollowMemberLiveData(result.data)
               }else{
                   systemViewModel?.setFollowMemberLiveData(null)
               }
            }
            override fun onError(code: Int, message: String?) {

            }
        })
    }


    /**
     * 测量数据
     */
    private fun getHealthMeasureData(userId : String?){
        moenPresenter.getHealthMeasure(null,userId,null,null,null,
            object : MirrorResultView<BaseResponse<HealthMeasure>>{
                override fun onSuccess(result: BaseResponse<HealthMeasure>?) {
                    try {
                        val value = Gson().fromJson(result?.data?.list?.get(0)?.log_content, HealthMeasure.LogContent::class.java)
                        tv_weight?.text = String.format("%.1f",value.weight)
                        tv_measure_update_time?.text = "最近测量:${result?.data?.list?.get(0)?.create_time}"
                        systemViewModel?.setHealthMeasureLiveData(result?.data)
                    }catch (e : Exception){
                        e.printStackTrace()
                        tv_weight?.text = "--"
                        tv_measure_update_time?.text = "最近测量:--"
                        systemViewModel?.setHealthMeasureLiveData(null)
                    }
                }
                override fun onError(code: Int, message: String?) {

                }
            })
    }


    /**
     * 测量趋势图
     */
    private fun getHealthChart(userId:String?){
        val  chartDayTV :TextView? =  chartInflateView?.findViewById(R.id.tv_chart_day)
        val  chartWeekTV :TextView? =  chartInflateView?.findViewById(R.id.tv_chart_week)

        chartDayTV?.setTextColor(resources.getColor(R.color.white))
        chartWeekTV?.setTextColor(resources.getColor(com.vercon.common.R.color.color_99B5BC))

        chartDayTV?.setOnClickListener {
            chartDayTV.setTextColor(resources.getColor(R.color.white))
            chartWeekTV?.setTextColor(resources.getColor(com.vercon.common.R.color.color_99B5BC))
            getHealthChartDayaOrWeek("day",userId)
        }
        chartWeekTV?.setOnClickListener {
            chartWeekTV.setTextColor(resources.getColor(R.color.white))
            chartDayTV?.setTextColor(resources.getColor(com.vercon.common.R.color.color_99B5BC))
            getHealthChartDayaOrWeek("week",userId)
        }


        val ig_to_see_more_data : LinearLayout?= chartInflateView?.findViewById(R.id.ig_to_see_more_data)
        ig_to_see_more_data?.setOnClickListener {
            FragmentOpenManager.getInstance().addFragment(requireActivity(),HealthFragment())
        }

        getHealthChartDayaOrWeek("day",userId)
    }

    private fun getHealthChartDayaOrWeek(day_week : String,userId: String?){
        moenPresenter.getMeasureTrendChart(day_week,null,null,null,null,userId,
            object : MirrorResultView<BaseResponse<MeasureTrendChart>>{
                override fun onSuccess(result: BaseResponse<MeasureTrendChart>?) {
                    var healthChartDate : Any? = null
                    try {
                        if(day_week.equals("day")){
                            val xLabel = ArrayList<String>()
                            val yData = ArrayList<Any>()
                            for((i,bean) in result?.data?.list?.withIndex()!!){
                                val array = arrayOfNulls<Any>(2)
                                array[0] = bean.name
                                if(bean.value != null){
                                    val value = Gson().fromJson(bean.value, MeasureTrendChart.valueBean::class.java)
                                    array[1] = value.getValue(HealthMeasureTarget.WEIGHT).toInt()
                                    yData.add(array)
                                }else{
                                    array[1] = 0
                                    yData.add(array)
                                }
                            }
                            if(yData.size == 0){
                                //造一个假数据
                                for ( i in 0..5) {
                                    val array = arrayOfNulls<Any>(2)
                                    if(i > 2){
                                        array[0] = sdf.format(Date()) + " " + (i*4).toString() +":00"
                                    }else{
                                        array[0] = sdf.format(Date()) +" 0" +(i*4).toString() +":00"
                                    }
                                    array[1] = 0
                                    yData.add(array)
                                }
                            }
                            healthChartDate = HealthChartDate()
                            healthChartDate.Data = yData
                            healthChartDate.xLabel = xLabel
                        }else{
                            healthChartDate  = HealthChartDate2()
                            val xLabel = ArrayList<String>()
                            val yData = ArrayList<Int>()
                            for((i,bean) in result?.data?.list?.withIndex()!!){
                                xLabel.add(MeasureTrendChart.xLabel("week",i))
                                if(bean.value != null ){
                                    val value = Gson().fromJson(bean.value, MeasureTrendChart.valueBean::class.java)
                                    yData.add(value.weight.toInt())
                                }
                            }
                            healthChartDate.Data = yData
                            healthChartDate.xLabel = xLabel
                        }

                    }catch (e:Exception){
                        e.printStackTrace()
                    }finally {
                        if(day_week.equals("day")){
                            webviewEcharts?.init("file:///android_asset/EChartViewTime.html")
                        }else{
                            webviewEcharts?.init("file:///android_asset/EChartView.html")
                        }
                        webviewEcharts?.setWebViewClient(object : WebViewClient() {
                            override fun onPageFinished(view: WebView, url: String) {
                                super.onPageFinished(view, url)
                                webviewEcharts?.refreshEchartsWithOption(healthChartDate)
                            }

                            override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
                                super.onPageStarted(view, url, favicon)
                            }
                        })
                    }
                }
                override fun onError(code: Int, message: String?) {

                }
            })
    }

    /**
     * 摩恩灵感
     */
    private fun getMoenAdList(){
        currentAdIndex = 0
        binding?.adWebLayout?.igGotAdWeb?.setOnClickListener {
            try {
                val data = binding?.adWebLayout?.bannerView?.data?.get(currentAdIndex) as Inspiration.ListDTO
                if(data.link?.length!! > 4 && data.link?.substring(0,4).equals("http")){
                    val intent = Intent(activity, WebKitWebViewActivity::class.java)
                    intent.putExtra(WebKitWebViewActivity.WEB_URL, data.link)
                    startActivity(intent)
                }else {
                    //ToastUtils.showToast("链接错误")
                }
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
        moenPresenter.moenAdList(object : MirrorResultView<BaseResponse<Inspiration>>{
            override fun onSuccess(result: BaseResponse<Inspiration>?) {
                if(result?.isSuccessful!!){
                    binding?.adWebLayout?.igGotAdWeb?.visibility = View.VISIBLE
                    val indicatorList = ArrayList<Int>()
                    for ((i,bean)in result.data.list.withIndex()){
                        indicatorList.add(i)
                    }
                    indicatorAdapter?.setData(indicatorList)
                    binding?.adWebLayout?.bannerView?.refreshData(result.data.list)
                }
            }
            override fun onError(code: Int, message: String?) {

            }
        })
    }

    /**
     * 天气
     */
    private fun autoGetWeather() {
        mainPresenter!!.getSimpleWeatherJuHe(
            "广州",
            object : MirrorResultView<NewWeatherSimpleBean?> {
                override fun onSuccess(result: NewWeatherSimpleBean?) {
                    try {
                        //天气描述
                        val data = result?.data
                        if (data?.future?.size!! > 0 && !TextUtils.isEmpty(data.future[0].weather)) {
                            val today = data.future!![0]
                            binding?.homeWeatherLayout?.tvWeatherName?.text = today.weather
                            if (!TextUtils.isEmpty(data.realtime.temperature)) {
                                //温度值
                                binding?.homeWeatherLayout?.tvWeather?.text = String.format("%s%s", data.realtime.temperature, WeatherUtils.getUnit())
                            }
                            //天气图标
                            binding?.homeWeatherLayout?.ivWeatherLottieIcon?.visibility = View.VISIBLE
                            binding?.homeWeatherLayout?.ivWeatherLottieIcon?.setAnimation(WeatherUtils.setLottieAminaJson(today.weather, 0))
                            binding?.homeWeatherLayout?.ivWeatherLottieIcon?.setImageAssetsFolder(WeatherUtils.setLottieAminaImageRes(today.weather, 0))
                            binding?.homeWeatherLayout?.ivWeatherLottieIcon?.repeatCount = LottieDrawable.INFINITE
                            binding?.homeWeatherLayout?.ivWeatherLottieIcon?.playAnimation()
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                override fun onError(code: Int, message: String) {}
            })
        mainPresenter!!.getAqi(
            "广州",
            object : MirrorResultView<BaseMode<AirAuality.ResultBean?>?> {
                override fun onSuccess(result: BaseMode<AirAuality.ResultBean?>?) {
                    try {
                        val resultBean = result?.data
                        if (resultBean != null) {
                            val string = WeatherUtils.getString(context, "AQI", resultBean.aqi)
                            binding?.homeWeatherLayout?.tvQuality?.text = string
                            Handler().postDelayed({
                                    try {
                                        WeatherUtils.setAqiHeight(context, resources.getDimension(com.vercon.common.R.dimen.dp_22), binding?.homeWeatherLayout?.ivAqi, resultBean.aqi.toInt())
                                    } catch (e: Exception) {
                                        e.printStackTrace()
                                    }
                            }, 1000)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                override fun onError(code: Int, message: String) {}
            })
    }

    /**
     * 除雾关闭倒计时
     */
    fun demistTask(){
        disposeDemistTask()
        Observable.interval(1, TimeUnit.MINUTES).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<Long?> {
                override fun onSubscribe(d: Disposable) {
                    demistDisposable = d
                }

                override fun onNext(t: Long) {
                    val time = systemViewModel?.demistTimeCountDown()
                    if(0 == time){
                        disposeDemistTask()
                        systemViewModel?.setIsOpenDemist(false,null)
                        EventBus.getDefault().post(BaseEvent(Constants.refreshDemist,false))
                    }
                }
                override fun onError(e: Throwable) {}
                override fun onComplete() {}
            })
    }
    fun disposeDemistTask(){
        demistDisposable?.dispose()
    }


    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun refreshApp(event: BaseEvent) {
        when (event.getType()) {
            Constants.refreshLight ->{
                binding?.lightSwitchLayout?.igLightState?.isSelected = event.content as Boolean
            }
            Constants.refreshDemist ->{
                binding?.demistSwitchLayout?.igDemistState?.isSelected = event.content as Boolean
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun refreshApp(event: WifiSuccessEvent) {
        Observable.timer(5,TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<Long?> {
                override fun onSubscribe(d: Disposable) {

                }

                override fun onError(e: Throwable) {

                }

                override fun onComplete() {

                }

                override fun onNext(t: Long) {
                    autoGetWeather()
                    getMoenAdList()
                    getAllData()
                    getUserInfo()
                }

            })
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (weatherDisposable != null) {
            weatherDisposable!!.dispose()
        }
        LightHelper.getInstance().onDestroy()
        EventBus.getDefault().unregister(this@HomeFragment)
        Settings.System.putInt(context?.contentResolver, SETTING_GPIO3,0)
        disposeDemistTask()
        binding?.adWebLayout?.bannerView?.onDestroy()
        activity?.viewModelStore?.clear()
        websocketMoen?.destroy()
    }

    /**********************          wifi监听            */
    override fun onScanResult(list: List<ScanResult>) {}
    override fun onNetWorkStateChanged() {}

    override fun onWiFiStateChanged() {}
    override fun onConnectFault() {}
    override fun onConnectSuccess(scanResult: ScanResult?) {
        //autoGetWeather();
    }

    override fun onDisconnected() {}
    override fun onConnecting() {}
    override fun onScaning() {}
}